package com.zengqingfa.imp.demo.rest;

import com.google.gson.Gson;
import com.zengqingfa.imp.demo.dto.InvChangeBillDto;
import com.zengqingfa.imp.demo.util.ExcelImportUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * @fileName: ExcelImportBillRest
 * @author: zengqf3
 * @date: 2020-12-20 10:47
 * @description:
 */
@RestController
@RequestMapping("/import")
@Slf4j
public class ExcelImportBillRest {

    public static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static final Gson gson = new Gson();

    @PostMapping("/bill")
    public String importBill(@RequestBody @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String filename = file.getOriginalFilename();
        //获取文件后缀名
        String suffix = filename.substring(filename.lastIndexOf('.') + 1);
        if (!Objects.equals(suffix, "xlsx") && !Objects.equals(suffix, "xls")) {
            throw new IllegalArgumentException("文件类型必须是[xlsx,xls]的其中一种.");
        }
        List<InvChangeBillDto> requestList = new ExcelImportUtil(InvChangeBillDto.class).readExcel(file, 1, 0);
        log.info("requestList:{}", gson.toJson(requestList));
        if (CollectionUtils.isEmpty(requestList)) {
            throw new IllegalArgumentException("导入的数据不能为空");
        }
        requestList.stream().forEach(b -> {
            b.getCreateTimes().stream().forEach(t -> {
                //时间转换
                LocalDateTime parse = LocalDateTime.parse(t, df);
                log.info("parseTime:{}", parse);
                b.setChangeTime(parse);
                //插入操作

            });
        });
        return "导入成功";
    }
}
